const api = require('../../utils/request.js');

Page({
  data: {
    gridItems: [{
        text: '排行榜',
        src: '/image/rank.png',
        pagePath: '/pages/rank/rank'
      },
      {
        text: '每日放送',
        src: '/image/feed.png',
        pagePath: '/pages/timetable/timetable'
      },
      {
        text: '搜索',
        src: '/image/search.png',
        pagePath: '/pages/search/search'
      }
    ],
    cardData: new Array(3).fill({}),
    activeDay: 0,
    weekDays: [{
      name: '周一'
    }, {
      name: '周二'
    }, {
      name: '周三'
    }, {
      name: '周四'
    }, {
      name: '周五'
    }, {
      name: '周六'
    }, {
      name: '周日'
    }],
    weekData: [],
    dayAnimeList: [],
    isLoading: false,
    imgList: [],
    leftColumn: [],
    rightColumn: [],
    columnWidth: [],
    offset: 0,
    limit: 30,
    isLoadingMore: false,
    hasMore: true
  },

  onLoad() {
    // wx.setStorageSync('username', '874339');
    this.fetchCardsData(); // 页面加载时拉取数据
    this.fetchTimetable();
    this.loadMoreData();
  },

  onShow() {
    if (this.getTabBar) {
      this.getTabBar().init();
    }
  },

  onGridItemClick(event) {
    const pagePath = event.currentTarget.dataset.path;
    if (pagePath) {
      wx.navigateTo({
        url: pagePath
      });
    } else {
      console.error('未配置页面路径');
    }
  },
//好书一览
  async fetchCardsData() {
    this.setData({
      isLoading: true
    }); // 👈 开始加载
    try {
      const {quarterStart} =  this.getCurrentQuarterDates();
      const body = {
        keyword: '',
        sort: 'heat',
        filter: {
          type: [1], //type: 条目类型，参照 SubjectType enum， 或。
          // meta_tags: [],//由维基人维护的 tag
          // tag: [],//tag: 标签，可以多次出现。且 关系。
          air_date: [">=" + quarterStart], //: 播出日期/发售日期。且 关系。
          // rating: [],//用于搜索指定评分的条目。且 关系。
          // rank: [],//rank: 用于搜索指定排名的条目。且 关系。
          nsfw: false
        }
      }
      const res = await api.searchSubjects(10, 0, body);
      if (Array.isArray(res.data)) {
        this.setData({
          cardData: res.data
        });
      }
    } catch (err) {
      console.error('网络请求失败:', err);
    } finally {
      this.setData({
        isLoading: false
      }); // 👈 加载完毕
    }
  },
  onFreshCardTap(e) {
    const subjectId = e.currentTarget.dataset.id;
    if (subjectId) {
      wx.navigateTo({
        url: `/pages/item-detail/item-detail?id=${subjectId}`
      });
    } else {
      console.error('好书一览卡片未找到 id');
    }
  },

  /*时间表*/
  onPushTitleClick() {
    wx.navigateTo({
      url: '/pages/timetable/timetable' // 
    });
  },
  async fetchTimetable() {
    this.setData({
      isLoading: true
    });
    try {
      const res = await api.getTimetable();
      if (!Array.isArray(res.data)) {
        throw new Error('时间表数据格式错误');
      }
      // 转换图片协议为 HTTPS
      const convertImagesToHttps = (item) => {
        if (item.images) {
          const newImages = {};
          for (const [key, value] of Object.entries(item.images)) {
            newImages[key] = value.replace('http://', 'https://');
          }
          return {
            ...item,
            images: newImages
          };
        }
        return item;
      };

      const processedWeekData = res.data.map(day =>
        day.map(item => convertImagesToHttps(item))
      );

      const today = new Date().getDay();
      const activeDay = today === 0 ? 6 : today - 1;
      const safeIndex = Math.max(0, Math.min(6, activeDay));
      this.setData({
        weekData: processedWeekData,
        activeDay: safeIndex,
        dayAnimeList: (processedWeekData[safeIndex] || []).slice(0, 3)
      });
    } catch (err) {
      console.error('获取时间表失败：', err);
      this.setData({
        weekData: Array(7).fill([]),
        dayAnimeList: []
      });
    } finally {
      this.setData({
        isLoading: false
      });
    }
  },

  onDayTabChange(e) {
    const index = e.detail.index;
    const {
      weekData
    } = this.data;
    this.setData({
      activeDay: index,
      dayAnimeList: weekData[index] ? weekData[index].slice(0, 3) : []
    });
  },
  onAnimeCardClick(e) {
    const item = e.detail.itemData;
    if (item) {
      wx.navigateTo({
        url: `/pages/item-detail/item-detail?id=${item.id}`
      });
    } else {
      console.error('未找到番剧 ID，跳转失败');
    }
  },

  onTouchStart(e) {
    const index = e.currentTarget.dataset.index;
    const newList = this.data.imgList.map((item, i) => ({
      ...item,
      active: i === index
    }));
    this.setData({
      imgList: newList
    });
  },

  onTouchEnd() {
    const newList = this.data.imgList.map(item => ({
      ...item,
      active: false
    }));
    this.setData({
      imgList: newList
    });
  },

  onImageTap(e) {
    const subjectId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/item-detail/item-detail?id=${subjectId}`
    });
  },

  onReachBottom() {
    if (!this.data.isLoadingMore && this.data.hasMore) {
      this.loadMoreData();
    }
  },

  // 获取当前季度的第一天和最后一天（格式：YYYY-MM-DD）
 getCurrentQuarterDates() {
  const today = new Date();
  const year = today.getFullYear();
  const month = today.getMonth(); // 0-11 (0代表1月)

  // 计算当前季度
  let quarterStart, quarterEnd;
  
  if (month >= 0 && month <= 2) {   // 第一季度 (1月-3月)
    quarterStart = `${year}-01-01`;
    quarterEnd = `${year}-03-31`;
  } else if (month >= 3 && month <= 5) {  // 第二季度 (4月-6月)
    quarterStart = `${year}-04-01`;
    quarterEnd = `${year}-06-30`;
  } else if (month >= 6 && month <= 8) {  // 第三季度 (7月-9月)
    quarterStart = `${year}-07-01`;
    quarterEnd = `${year}-09-30`;
  } else {  // 第四季度 (10月-12月)
    quarterStart = `${year}-10-01`;
    quarterEnd = `${year}-12-31`;
  }

  return {
    quarterStart,
    quarterEnd
  };
},


  async loadMoreData() {
    this.setData({
      isLoadingMore: true
    });
    try {
      const {
        offset,
        limit,
        imgList
      } = this.data;
      const {quarterStart} =  this.getCurrentQuarterDates();
      const body = {
        keyword: '',
        sort: 'heat',
        filter: {
          type: [1, 2, 3, 4, 6], //type: 条目类型，参照 SubjectType enum， 或。
          // meta_tags: [],//由维基人维护的 tag
          // tag: [],//tag: 标签，可以多次出现。且 关系。
          air_date: [">=" + quarterStart], //: 播出日期/发售日期。且 关系。
          // rating: [],//用于搜索指定评分的条目。且 关系。
          // rank: [],//rank: 用于搜索指定排名的条目。且 关系。
          nsfw: false
        }
      }
      const res = await api.searchSubjects(limit, offset, body);

      const newList = res.data.map(item => ({
        id: item.id,
        image: item.images?.large,
        ratio: 1.5
      })).filter(item => !!item.image);

      if (newList.length === 0) {
        this.setData({
          hasMore: false
        });
        return;
      }

      const updatedList = imgList.concat(newList);
      this.setData({
        imgList: updatedList,
        offset: offset + limit
      }, () => {
        this.initColumns();
      });
    } catch (err) {
      console.error("加载更多失败", err);
    } finally {
      this.setData({
        isLoadingMore: false
      });
    }
  },

  initColumns() {
    const left = [];
    const right = [];

    this.data.imgList.forEach((item, index) => {
      if (index % 2 === 0) {
        left.push(item);
      } else {
        right.push(item);
      }
    });

    this.setData({
      leftColumn: left,
      rightColumn: right
    });
  }


});